<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="inside">0</div>
  <button id="start">开始</button>
  <button id="end">结束</button>
  <script>
    let inside = document.querySelector('#inside')
    let start = document.querySelector('#start')
    let end = document.querySelector('#end')
    let count = 0
    function addCount (e) {
      console.log(e.target, this);
      inside.innerHTML = ++count
      return count
    }
    function debounce (fn, wait, immediate) {
      let timer, result
      let debounceFn = function () {
        let context = this
        let args = arguments
        if (timer) clearTimeout(timer)
        if (immediate) {
          let callNow = !timer // 第一次点击此时的timer为空
          timer = setTimeout(() => { // 后续的点击timer就有值了 怎么点击都不会调用这个函数
            timer = null
          }, wait);
          if (callNow) result = fn.apply(context, args)
        } else {
          timer = setTimeout(() => {
            fn.apply(context, args)
          }, wait);
        }
        return result
      }
      debounceFn.cancel = function () {
        if (timer) clearTimeout(timer)
        timer = null
      }
      return debounceFn
    }
    let debounceed = debounce(addCount, 10000, true)
    start.addEventListener('click', function () {
      let result = debounceed.apply(this, arguments)
      console.log('返回值是', result);
    })
    end.addEventListener('click', debounceed.cancel)
  </script>
</body>

</html>